package HtServer.meeting;
import jakarta.websocket.ClientEndpoint;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.CountDownLatch;

@ClientEndpoint
public class TestWebSocketClient extends WebSocketClient {

    private final CountDownLatch connectLatch = new CountDownLatch(1);
    public TestWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        System.out.println("onOpen");
        connectLatch.countDown();
    }

    @Override
    public void onMessage(String message) {
        System.out.println("onMessage: " + message.length());
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        System.out.println("onClose: " + code + ", " + reason + ", " + remote);
    }

    @Override
    public void onError(Exception ex) {
        System.out.println("onError: " + ex);
    }
    public void waitForConnection() throws InterruptedException {
        connectLatch.await();
    }
    public  static void main(String[] argv)
    {
        for (int i = 0; i < 1; i++) {
            new Thread() {
                public void run() {
                    try {
                        try {
                            URI serverUri = new URI("ws://localhost:8080/MWS?isMobile=true");
                            TestWebSocketClient client = new TestWebSocketClient(serverUri);
                            client.connect();

                            // Wait for the connection to be established
                            client.waitForConnection();

                            // Send a message to the server
                            client.send("{\"type\":\"3\"} ");

                            // Keep the connection open for 5 seconds
                            Thread.sleep(50);

//            client.close();
                        } catch (URISyntaxException | InterruptedException e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

    }

}
